from dao.department_dao import (get_departments_dao)
from dao.major_dao import (get_majors_by_f_id_dao)
from dao.grade_dao import (get_grades_by_m_id_dao)
from dao.at_class_dao import (get_record)
from dao.course_dao import (get_course_by_course_id)
from dao.user_dao import (get_student_by_user_id)


def get_d_m_c_service():
    d_m_c = []
    all_departments = get_departments_dao()
    for department in all_departments:
        d = {}
        majors_of_department = get_majors_by_f_id_dao(department["f_id"])
        d["value"] = department["f_id"]
        d["label"] = department["f_name"]
        d["children"] = []
        for major in majors_of_department:
            m = {}
            grades_of_major = get_grades_by_m_id_dao(major["m_id"])
            m["value"] = major["m_id"]
            m["label"] = major["m_name"]
            m["children"] = []
            for grade in grades_of_major:
                c = {}
                c["value"] = grade["c_id"]
                c["label"] = grade["c_name"]
                m["children"].append(c)
            d["children"].append(m)
        d_m_c.append(d)
    return d_m_c


def get_today_calls_service(data):
    week = data[0]
    day = data[1]
    f_id = data[2]
    m_id = data[3]
    c_id = data[4]
    res = {}
    at_class_calls = get_record(
        sql="""
        select * from `se_at_class` 
        where `week`={} and `day`={} and `major_id`={} and `class_id`={}
        """.format(week, day, m_id, c_id)
    )
    ress = []
    for record in at_class_calls:
        course = get_course_by_course_id(record["course_id"])[0]
        if res.__contains__(record["user_id"]):
            res[record["user_id"]]["course"].append({
                "course_name": course["name"],
                "course_state": record["state"]
            })
        else:
            student = get_student_by_user_id(record["user_id"])
            res[record["user_id"]] = {}
            res[record["user_id"]]["id"] = record["id"]
            res[record["user_id"]]["user_id"] = record["user_id"]
            res[record["user_id"]]["u_num"] = student["u_num"]
            res[record["user_id"]]["u_name"] = student["u_name"]
            res[record["user_id"]]["course"] = []
            res[record["user_id"]]["course"].append({
                "course_name": course["name"],
                "course_state": record["state"]
            })

    for k in res:
        ress.append(res[k])
    print(ress)
    return ress